"use client"

import { createContext, useContext, useEffect, useState, ReactNode } from 'react'
import { useRouter } from 'next/navigation'

interface AuthContextType {
    isAuthenticated: boolean
    isLoading: boolean
    logout: () => Promise<void>
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: ReactNode }) {
    const [isAuthenticated, setIsAuthenticated] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const router = useRouter()

    useEffect(() => {
        async function checkAuthentication() {
            try {
                // 在客户端，我们只能通过API检查认证状态
                const res = await fetch('/api/auth/check', {
                    credentials: 'include'
                })

                if (!res.ok) {
                    throw new Error('Not authenticated')
                }

                const { isAuthenticated } = await res.json()
                setIsAuthenticated(isAuthenticated)
            } catch (error) {
                console.error('Authentication check failed:', error)
                router.push('/login')
            } finally {
                setIsLoading(false)
            }
        }

        checkAuthentication()
    }, [router])

    const logout = async () => {
        await fetch('/api/auth/logout', {
            method: 'POST',
            credentials: 'include'
        })
        setIsAuthenticated(false)
        router.push('/login')
    }

    return (
        <AuthContext.Provider value={{ isAuthenticated, isLoading, logout }}>
            {children}
        </AuthContext.Provider>
    )
}

export function useAuth() {
    const context = useContext(AuthContext)
    if (context === undefined) {
        throw new Error('useAuth must be used within an AuthProvider')
    }
    return context
}